<?php
/**
 * Created by PhpStorm
 * User: 龍zero
 * Date: 2022-04-10
 * Time: 16:28
 */
declare(strict_types=1);

namespace App\Service;


use App\Exception\ParameterException;
use App\Lib\Enum\IdentityConstant;
use App\Model\LinUserIdentity;

class UserIdentityService
{
    public function verifyUsernamePassword($uid,$username,$password){
        $userIdentity = LinUserIdentity::where('user_id',$uid)
            ->where('identifier',$username)
            ->where('identity_type',IdentityConstant::USERNAME_PASSWORD_IDENTITY)
            ->first();
        return  password_verify_pbkdf2($password,$userIdentity->credential);
    }


    /**
     * 创建建用户认证信息
     * @param int $userId
     * @param string $username
     * @param string $password
     */
    public function createUsernamePasswordIdentity(int $userId,string $username,string $password){
        $userIdentity = new LinUserIdentity;
        $userIdentity->user_id = $userId;
        $userIdentity->identity_type = IdentityConstant::USERNAME_PASSWORD_IDENTITY;
        $userIdentity->identifier = $username;
        $userIdentity->credential = password_hash_pbkdf2($password);
        $userIdentity->save();
    }

    public function changePassword($id,$password){
        $userIdentity = LinUserIdentity::where('user_id',$id)
            ->where('identity_type',IdentityConstant::USERNAME_PASSWORD_IDENTITY)->first();
        if(!$userIdentity){
            throw new ParameterException(10021);
        }
        $userIdentity->credential = password_hash_pbkdf2($password);
        $userIdentity->save();
    }
}